import React, {useEffect, useRef, useState} from "react";
import {useStatistics} from "../../hooks/useStatistics";
import {FlatList, RefreshControl, StyleSheet, View,Text,Platform, Alert,Modal,TouchableOpacity} from "react-native";
import StatisticsItem from "./StatisticsItem";
import EmptyView from "../../components/EmptyView";
import Header from "../Home/Header";
import LevelView from "../../components/Level";
import PercentView from "../../components/PercentView";
import {IStatistics} from "../../types/statistics";
import {useIsFocused} from "@react-navigation/native";
import SkeletonView from "../../components/Skeleton";
import {NativeBaseProvider, Button,Switch,CloseIcon} from "native-base";
import {colors, moodsColors, moodsConfig, windowWidth} from "../../utils/config";
import CirclePercentage from "../../components/PercentView/CirclePercentage";
import {getCircleData} from '../../services/index.ts'

export function Statisticslist(props) {

    const isFocused = useIsFocused();
    const [dateTime, setDateTime] = useState([]);
    const [dateTimeWithoutYear, setDateTimeWithoutYear] = useState([]);
    const [ parentData, setParentData ] = useState({});
    const [ parentId, setParentId ] = useState('');
    const [ lastEventName, setLastEventName ] = useState('');
    const [ level, setLevel ] = useState(0);
    const [ selectPeriod, setSelectPeriod, ] = useState(false);
    const levelViewRef = useRef(null);
    const headerRef = useRef(null);
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    const { statistics, selectIndex,eventsName } = useStatistics();

    const [ showType,setShowType ] = useState(2)
    const [isEnabled, setIsEnabled] = useState(false);
    const [showModal, setShowModal] = useState(false);
    const [circleData, setCircleData] = useState([]);
    const [lastName, setLastName] = useState('');



    const getCircleDataFun = (level,eventId,name)=>{
        let obj = {
            level,
            eventId,
            startDate:dateTime[0],
            endDate:dateTime[1],
        }
        console.log(obj)
        getCircleData(obj).then(res=>{
            console.log(1323333)
            console.log(dateTime)
            console.log(1323333)
            setLastName(name)
            setCircleData(res.data && res.data.length ? res.data : [])
            setShowModal(true)
        })
    }

    

    useEffect(() => {
        if (isFocused && dateTime.length > 0) {
            onRefresh();
        }
        setTimeout(()=>{
            
        },2000)
    },[isFocused]);

    const toggleSwitch = () => {

        setIsEnabled(previousState => {
            if(!previousState){
                setShowType(1)
            }else{
                setShowType(2)
            }
            return !previousState
        });
    }

    const onRefresh = () => {
        setLastEventName('');
        setRefreshing(true);
        levelViewRef?.current?.refresh();
    }

    const onEndReached = () => {
        //todo 分页加载
    }

    const renderEmptyComponent = () => {
        return <EmptyView/>;
    }

    

    const renderHeader = () => {
        if (statistics.length > 0) {
            return <PercentView
                showType={showType}
                lastEventName={lastEventName}
                clickUp={() => {
                    setLastEventName('');
                    levelViewRef?.current?.loadParentData(parentData?.level === 2 ? parentId:'' ,level);
                    setLevel(level > 1 ? level - 1 : level);
                }}
            />
        } else {
            return null;
        }
    }

    function renderItem({ item,index }: { item: IStatistics }) {
        return (
            <StatisticsItem
                statistics={statistics}
                index = {index} {...item}
                showType = {showType}
                itemCallback={()=>{
                    if(!item.recorded) return;
                    if(!item?.hasChildren && selectIndex == 2){
                        getCircleDataFun(item.level,item.id,item.name)
                        return
                    }

                    
                    if (item.level === 3) return;
                    if (!item?.hasChildren) return;
                    if (item.level === 1) {
                        setParentId(item.id);
                    }
                    setParentData(item);
                    setLevel(item.level);
                    setLastEventName(item.name);
                    levelViewRef?.current?.loadParentData(item.id,item.level + 1);
                }}
            />
        );
    }

    console.log('-----statisticslist------',statistics)

    const renderSeparatorComponent = () => {
        return <View style={styles.separatorStyle}></View>
    }

    return (
        <NativeBaseProvider >
            <View style={styles.container}>
                <Header
                    from={'statistics'}
                    ref={headerRef}
                    selectPeriod = {selectPeriod}
                    iconClick={()=>{
                        props.navigation.navigate('EventsChart');
                    }}
                    selectedRangeCallback={(period)=>{
                        if (period.length === 2) {
                            setDateTime(period);
                            let newDateBeforeSevenDay = period[0].split('-');
                            newDateBeforeSevenDay.splice(0,1);
                            let newCurrentDay = period[1].split('-');
                            newCurrentDay.splice(0,1);
                            setDateTimeWithoutYear([newDateBeforeSevenDay.join('.'),newCurrentDay.join('.')]);
                            setSelectPeriod(true);
                            levelViewRef?.current?.loadSetDateTimeWithoutYear([newDateBeforeSevenDay.join('.'),newCurrentDay.join('.')]);
                            levelViewRef?.current?.loadCalculateData(period[0],period[1]);
                        }
                    }}
                    selectDateCallback = {(date)=>{
                        levelViewRef?.current?.reLoadTimeSlot(date);
                    }}
                    toggleModalCallback={()=>{
                        setSelectPeriod(false);
                    }}
                />

                <LevelView
                    from={'staticstics'}
                    ref={levelViewRef}
                    selectPeriod={selectPeriod}
                    dateTime={dateTime}
                    dateTimeWithoutYear={dateTimeWithoutYear}
                    periodCallback={(type) => {
                        setSelectPeriod(type);
                    }}
                    clickPeriodDate={() => {
                        setSelectPeriod(true);
                        setTimeout(()=>{
                            headerRef?.current?.toggleModal();
                        },10)
                    }}
                    dateCallback={(date)=>{
                        setDateTime(date);
                    }}
                    clearEventNameCallback={()=>{
                        setLastEventName('');
                    }}
                    loadCallback={()=>{
                        setRefreshing(false);
                        setLoading(false);
                    }}
                />

                {
                    loading ?
                        <SkeletonView/>
                        :
                        <FlatList
                            data={statistics}
                            style={styles.flatListStyle}
                            refreshControl={
                                <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={onRefresh}
                                    tintColor="rgba(67, 113, 177, 1)"
                                    // title="Loading..."
                                    // titleColor="rgba(198, 224, 247, 1)"
                                    // size={0}
                                    colors={["rgba(67, 113, 177, 1)"]}
                                    progressBackgroundColor="white"
                                />
                            }
                            ItemSeparatorComponent={renderSeparatorComponent}
                            onEndReached={onEndReached}
                            renderItem={renderItem}
                            keyExtractor={(item,index) => "statistics_"+index}
                            showsVerticalScrollIndicator={false}
                            ListEmptyComponent={renderEmptyComponent}
                            ListHeaderComponent={renderHeader}
                            ListFooterComponent={()=>{
                                return <View style={{height:70}}></View>
                            }}
                        />
                }
                {
                    statistics && statistics.length 
                    ?
                    <View style={{position:'absolute',bottom:0,flexDirection:'row',width:'100%',paddingHorizontal:18,justifyContent:"space-between"}}>
                        <View style={styles.percentTypeView}>
                            <Switch size={ Platform.OS === 'android' ? 'md' : 'sm' } offTrackColor="#eee" onTrackColor="#3076D9" onToggle={toggleSwitch} value={isEnabled} />
                            <Text style={{fontSize:14,color:'#2C2C2E',fontFamily:'HarmonyOS Sans SC',marginLeft:5}}>是否显示未记录时间</Text>
                        </View>
                    </View>
                    :
                    ''
                    }
            </View>


            <PopModal showModal={showModal} selectIndex={selectIndex} eventsName={eventsName} lastName={lastName} circleData={circleData} setShowModal={setShowModal}></PopModal>
        </NativeBaseProvider>
    );
}

const PopModal = ({showModal,setShowModal,circleData=[],eventsName,lastName,selectIndex}:any)=>{
    // const [segments ,setSegments] = useState([])
   let segments = []
   if (circleData?.length > 0) {
        circleData.map((item,index)=>{
            if (item?.percent != 0) {
                segments.push({
                    percentage: parseInt(String((item?.percent || 0) * 100)),
                    color: moodsColors[item?.type || '0']
                })
            }
        })
    }

   
    

 


    return(
        <Modal visible={showModal} transparent={true} onRequestClose={() => setShowModal(false)} >
                <View style={{flex:1,backgroundColor:'rgba(0,0,0,.3)',alignItems:'center',justifyContent:'center'}}>
                    <View style={{minHeight:263,width:'90%',backgroundColor:'#fff',borderRadius:21,paddingHorizontal:16,
                paddingVertical:19,}}>
                        <View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}>
                            <Text style={{fontSize:16,color:'#000000',fontWeight:'700', fontFamily:'HarmonyOS Sans SC'}}>{eventsName ?  eventsName + "-" +lastName : lastName}</Text>
                            <TouchableOpacity onPress={()=>{setShowModal(false)}}>
                                <CloseIcon color={'#414F66'} size="5"  />
                            </TouchableOpacity>
                        </View>
                        <View style={{borderWidth:4,borderColor:'#E8E8E8',width:70,height:32,alignItems:'center',justifyContent:'center',borderRadius:12,marginTop:20}}>
                            <Text style={{fontSize:12,color:'#000000',fontWeight:'700', fontFamily:'HarmonyOS Sans SC'}}>效率</Text>
                        </View>
                        <View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-around',marginTop:20}}>

                            <CirclePercentage size={113} strokeWidth={20} segments={segments}></CirclePercentage>
                            <View>
                                {
                                    (circleData || []).map((item,index)=>{
                                        return (
                                            <View style={styles.circleListView} key={'circlePer_'+index}>
                                                <View style={[styles.circleDot,{backgroundColor:  moodsColors[item?.type || '0']}]}></View>
                                                <Text style={styles.circleName}>{moodsConfig[item?.type]}</Text>
                                                <Text style={styles.circlePer}>{parseInt(String((item?.percent || 0) * 100))}% {selectIndex == 2 ? `${item?.time || 0}h` : ''}</Text>
                                            </View>
                                        )
                                    })
                                }
                            </View>
                            
                        </View>
                    </View>
                </View>
            </Modal>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'rgba(244, 244, 244, 1)',
    },
    flatListStyle: {
        flex: 1,
        backgroundColor: 'rgba(244, 244, 244, 1)',
        borderRadius: 16,
        marginHorizontal: 16,
        overflow: 'hidden',
    },
    separatorStyle: {
        height: 2,
        backgroundColor: 'rgba(244,244,244,1)',
    },
    percentTypeView: {
        backgroundColor: '#fff',
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 12,
        borderRadius: 12,
        paddingHorizontal: 12,
        paddingVertical:5,
        // flex:1,
        shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.2)', // 阴影颜色
        shadowOffset: { width: 0, height: 2 }, // 阴影偏移
        shadowOpacity: 1, // 阴影不透明度
        shadowRadius: 2, // 阴影半径
        elevation: 2, // 阴影深度
    },
    circleListView: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 6
    },
    circleDot: {
        width: 8,
        height: 8,
        borderRadius: 4,
        marginRight: 5,
    },
    circleName: {
        color: 'rgba(72, 72, 74, 1)',
        fontSize: 12,
        width: 80,
        fontFamily:'HarmonyOS Sans SC',
        lineHeight:18
    },
    circlePer: {
        color: 'rgba(142, 142, 147, 1)',
        fontSize: 12,
        fontFamily:'HarmonyOS Sans SC',
        lineHeight:18
    },
});
